package com.spzx.user.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.user.domain.Region;
import com.spzx.user.domain.UserAddress;
import com.spzx.user.service.IRegionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.spzx.user.mapper.UserAddressMapper;
import com.spzx.user.service.IUserAddressService;

/**
 * 用户地址Service业务层处理
 *
 * @author atguigu
 * @date 2024-07-10
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService
{
    @Resource
    private UserAddressMapper userAddressMapper;
    @Resource
    IRegionService regionService;

    @Override
    public boolean saveAddress(UserAddress userAddress) {
        //用户新增的地址如果是默认地址，需要将之前的默认地址改为非默认
        if(userAddress.getIsDefault().longValue() == 1l){
            //修改之前的默认地址为非默认
            this.update(Wrappers.lambdaUpdate(UserAddress.class)
                    .eq(UserAddress::getUserId , SecurityContextHolder.getUserId())
                    .eq(UserAddress::getIsDefault , 1)
                    .set(UserAddress::getIsDefault , 0));
        }

        //地址绑定用户
        userAddress.setUserId(SecurityContextHolder.getUserId());
        //获取省市区名称拼接 address
        Region province = regionService.selectRegionByCode(userAddress.getProvinceCode());
        Region city = regionService.selectRegionByCode(userAddress.getCityCode());
        Region district = regionService.selectRegionByCode(userAddress.getDistrictCode());
        userAddress.setFullAddress(province.getName()+" "+ city.getName() +" "+
                district.getName()+" "+ userAddress.getAddress());
        boolean save = this.save(userAddress);
        return save;
    }
}
